<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\WatchRequest;
use App\Models\Movie;
use App\Transformers\UserTransformer;
use App\Models\MovieWatchUser;
use Carbon\Carbon;
class WatchController extends Controller
{
    public function store(Movie $movie)
    {
        $this->user()->watching($movie);

        return $this->response->item($this->user(), new UserTransformer());
    }

    public function destory(Movie $movie)
    {
        $this->user()->unWatch($movie);
        return $this->response->item($this->user(), new UserTransformer());
    }

    public function update(Movie $movie, WatchRequest $request)
    {

        if ($request->status === 'watching') {
            $movie->watching($this->user());
        } else {
            // 判断时间
            $add_watching_time = Carbon::createFromTimeString($movie->last_watched_at($this->user()));
            $watch_time = $add_watching_time->diffInMinutes(Carbon::now());
            if ($watch_time < $movie->runtime) {
                return $this->response->error('打卡失败,请在 ' . ($movie->runtime - $watch_time) . '分钟后再来打卡！', 403);
            }
            $movie->watched($this->user());
            // 计数加1
            // MovieWatchUser::where('user_id', $this->user()->id)->where('movie_id', $movie->id)->increment('count');
        }
        $watch = MovieWatchUser::where('user_id', $this->user()->id)->where('movie_id', $movie->id)->first();
        return $this->response->item($this->user(), new UserTransformer())
                ->addMeta('status', $request->status)
                ->addMeta('watch_status', $this->watchStatus($watch))
                ->addMeta('count', $watch->count);
    }

    protected function watchStatus($watch)
    {
        switch($watch->status) {
            case 'watching' :
                $res = $watch->updated_at->diffForHumans() . '开始打卡';
            break;
            case 'watched' :
                $res = $watch->updated_at->diffForHumans() . '刷过';
            break;
            case 'inCollect' :
                $res = $watch->updated_at->diffForHumans() . '加入看单';
            break;
            default:
                $res = '从未刷过';
        }
        return $res;
    }
}
